package cn.message.web;

import cn.itcast.pojo.classsify;
import cn.itcast.util.OutputStringController;
import cn.message.service.IClassifyService;
import cn.web.web_module.util.IconPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 郭智超
 * @create 2020-03-28 9:53
 * 商品控制器
 */
@Slf4j
@RestController
@RequestMapping(value="/dhn/message",produces="text/html;charset=UTF-8")
public class ClassifyController {

    @Resource
    private IClassifyService classifyService;

    @Resource
    OutputStringController osc;


    @RequestMapping("/getAllClassify")
    @ResponseBody
    public String getAllClassify(@RequestBody Map<String,String> map, classsify classsify){
        String results = "";
        //获取前台提交的数据
        Integer page = Integer.parseInt(map.get("page"));
        Integer limit = Integer.parseInt(map.get("limit"));

        Map<String, Object> resultMap = classifyService.getAllClassify(page, limit, classsify);
        //获取所有商品分类列表信息
        Object classsifyList = resultMap.get("classsifyList");
        //获取符合查询条件的总记录条数
        int count = (int)resultMap.get("count");

        if(classsifyList == null){
            results = osc.resultFailure("no", "");
            log.debug("查询所有商品分类信息失败");
        }
        else {
            results = osc.resultSuccess("yes",classsifyList, count);
            log.debug("查询所有商品分类信息成功");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/deleteClassifyById")
    public String deleteClassifyById(@RequestBody Map<String,Integer> map){
        String results = "";
        int id = map.get("id");
        Boolean aBoolean = classifyService.deleteClassifyById(id);
        if(aBoolean == false){
            results = osc.resultFailure("系统异常，删除失败", "");
        }
        else {
            results = osc.success("yes");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/getAllMainClassifyName")
    public String getAllMainClassifyName(){
        String results = "";
        List<classsify> classsifies = classifyService.getAllMainClassifyName();
        if(classsifies.size() < 0){
            results = osc.failure("查询所有主分类名称失败");
        }else {
            results = osc.resultSuccess("查询所有主分类名称成功",classsifies);
        }

        return results;
    }

    @ResponseBody
    @PostMapping(value = "/addMainClassify",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addMainClassify(HttpServletRequest request,
                              @RequestParam(value = "number",required = false) String number,
                              @RequestParam(value = "name",required = false) String name,
                              @RequestParam(value = "minimum",required = false) Double minimum,
                              @RequestParam(value = "highest",required = false) Double highest,
                              @RequestParam(value = "settlementPrice",required = false) Double settlementPrice,
                              @RequestParam(value = "measure",required = false) String measure,
                              @RequestParam(value = "firstDistribution",required = false) String firstDistribution,
                              @RequestParam(value = "secondDistribution",required = false) String secondDistribution,
                              @RequestParam(value = "icon",required = false) MultipartFile icon) {

        String results = "";
        System.out.println(icon.getOriginalFilename());
        if (number.isEmpty()) {
            return osc.failure("编号不能为空，请添加编号");
        }
        if (name.isEmpty()) {
            return osc.failure("名称不能为空,请填写名称");
        }
        if (measure == null || measure.equals("")) {
            return osc.failure("商品计量单位不能为空，请选择计量单位");
        }
        if (icon.isEmpty()) {
            return osc.failure("请上传图片");
        }
        if (minimum == null || minimum.equals("")) {
            return osc.failure("最低参考价格不能为空，请填写最低参考价格");
        }
        if (highest == null || highest.equals("")) {
            return osc.failure("最高参考价格不能为空，请填写最高参考价格");
        }
        if (settlementPrice == null || settlementPrice.equals("")) {
            return osc.failure("结算价格不能为空，请填写结算价格");
        }
        if (firstDistribution == null || firstDistribution.equals("")) {
            return osc.failure("一级分销不能为空，请填写一级分销");
        }
        if (secondDistribution == null || secondDistribution.equals("")) {
            return osc.failure("二级分销不能为空，请填写二级分销");
        }

        classsify classsify = new classsify();
        classsify.setFid(0);
        classsify.setNumber(number);
        classsify.setName(name);
        classsify.setRegistrationTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        classsify.setMinimum(minimum);
        classsify.setHighest(highest);
        classsify.setSettlementPrice(settlementPrice);
        classsify.setMeasure(measure);
        classsify.setPreviousProfit(firstDistribution);
        classsify.setPreviousTwoProfit(secondDistribution);

        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/type/";//松注释
        String iconPath = IconPath.ICONPATH +"icon/type/";

//        String iconPathEnum = "E:/job/testIconPath";
        FileOutputStream fos = null;
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
//        classsify.setIcon("http://120.79.51.10:8181/dhn/icon/type/"+iconName);
//        classsify.setIcon("https://www.vaiq.cn:8181/dhn/icon/type/"+iconName);
            classsify.setIcon("https://www.dhnep.cn:8181/dhn/icon/type/"+iconName);
//        classsify.setIcon("E:/job/testIconPath"+iconName);
        Boolean aBoolean = classifyService.addClassify(classsify);
        if (!aBoolean) {
            results = osc.failure("添加失败");
        } else {
            results = osc.success("添加成功");
        }
        return results;
        }

    @ResponseBody
    @PostMapping(value = "/addchildrenClassify",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addchildrenClassify(HttpServletRequest request,
                              @RequestParam(value = "number",required = false) String number,
                              @RequestParam(value = "name",required = false) String name,
                              @RequestParam(value = "minimum",required = false) Double minimum,
                              @RequestParam(value = "highest",required = false) Double highest,
                              @RequestParam(value = "settlementPrice",required = false) Double settlementPrice,
                              @RequestParam(value = "measure",required = false) String measure,
                              @RequestParam(value = "id",required = false) Integer id,
                              @RequestParam(value = "firstDistribution",required = false) String firstDistribution,
                              @RequestParam(value = "secondDistribution",required = false) String secondDistribution,
                              @RequestParam(value = "icon",required = false) MultipartFile icon) {

        String results = "";
        System.out.println(icon.getOriginalFilename());
        //判断图片是否为空
        if (number.isEmpty()) {
            return osc.failure("编号不能为空，请添加编号");
        }
        if (name.isEmpty()) {
            return osc.failure("名称不能为空,请填写名称");
        }
        if (id == null || id.equals("")) {
            return osc.failure("商品所属主分类不能为空，请选择主分类");
        }
        if (measure == null || measure.equals("")) {
            return osc.failure("商品计量单位不能为空，请选择计量单位");
        }
        if (icon.isEmpty()) {
            return osc.failure("请上传图片");
        }
        if (minimum == null || minimum.equals("")) {
            return osc.failure("最低参考价格不能为空，请填写最低参考价格");
        }
        if (highest == null || highest.equals("")) {
            return osc.failure("最高参考价格不能为空，请填写最高参考价格");
        }
        if (settlementPrice == null || settlementPrice.equals("")) {
            return osc.failure("结算价格不能为空，请填写结算价格");
        }
        if (firstDistribution == null || firstDistribution.equals("")) {
            return osc.failure("一级分销不能为空，请填写一级分销");
        }
        if (secondDistribution == null || secondDistribution.equals("")) {
            return osc.failure("二级分销不能为空，请填写二级分销");
        }

        classsify classsify = new classsify();
        classsify.setFid(id);
        classsify.setNumber(number);
        classsify.setName(name);
        classsify.setRegistrationTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        classsify.setMinimum(minimum);
        classsify.setHighest(highest);
        classsify.setSettlementPrice(settlementPrice);
        classsify.setMeasure(measure);
        classsify.setPreviousProfit(firstDistribution);
        classsify.setPreviousTwoProfit(secondDistribution);

        //设置文件存储路径
//        String iconPathEnum = "/usr/tomcat/images/dhn/icon/type/";  //松注释

        String iconPath = IconPath.ICONPATH +"icon/type/";  //松新写
//        String iconPathEnum = "E:/job/testIconPath";
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
//        classsify.setIcon("http://120.79.51.10:8181/dhn/icon/type/"+iconName);
        classsify.setIcon("https://www.dhnep.cn:8181/dhn/icon/type/"+iconName);
//        classsify.setIcon("E:/job/testIconPath"+iconName);
        Boolean aBoolean = classifyService.addClassify(classsify);
        if (!aBoolean) {
            results = osc.failure("添加失败");
        } else {
            results = osc.success("添加成功");
        }
        return results;
    }

    @ResponseBody
    @PostMapping(value = "/updateClassify",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateClassify(HttpServletRequest request,
                                      @RequestParam(value = "number",required = false) String number,
                                      @RequestParam(value = "name",required = false) String name,
                                      @RequestParam(value = "minimum",required = false) Double minimum,
                                      @RequestParam(value = "highest",required = false) Double highest,
                                      @RequestParam(value = "settlementPrice",required = false) Double settlementPrice,
                                      @RequestParam(value = "measure",required = false) String measure,
                                      @RequestParam(value = "firstDistribution",required = false) String firstDistribution,
                                      @RequestParam(value = "secondDistribution",required = false) String secondDistribution,
                                      @RequestParam(value = "id",required = false) Integer id,
                                      @RequestParam(value = "type",required = false) Integer fid) {

        System.out.println("开始执行updateClassify方法了-------------------------------------------------------------------");
        String results = "";
        System.out.println(id);
        System.out.println(fid);

        if (number.isEmpty()) {
            return osc.failure("编号不能为空，请添加编号");
        }
        if (name.isEmpty()) {
            return osc.failure("名称不能为空,请填写名称");
        }
        if (id == null || id.equals("")) {
            return osc.failure("商品所属主分类不能为空，请选择主分类");
        }
        if (measure == null || measure.equals("")) {
            return osc.failure("商品计量单位不能为空，请选择计量单位");
        }
        if (minimum == null || minimum.equals("")) {
            return osc.failure("最低参考价格不能为空，请填写最低参考价格");
        }
        if (highest == null || highest.equals("")) {
            return osc.failure("最高参考价格不能为空，请填写最高参考价格");
        }
        if (settlementPrice == null || settlementPrice.equals("")) {
            return osc.failure("结算价格不能为空，请填写结算价格");
        }
        if (firstDistribution == null || firstDistribution.equals("")) {
            return osc.failure("一级分销不能为空，请填写一级分销");
        }
        if (secondDistribution == null || secondDistribution.equals("")) {
            return osc.failure("二级分销不能为空，请填写二级分销");
        }

        classsify classsify = new classsify();
        classsify.setId(id);
        classsify.setFid(fid);
        classsify.setNumber(number);
        classsify.setName(name);
        classsify.setRegistrationTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        classsify.setMinimum(minimum);
        classsify.setHighest(highest);
        classsify.setSettlementPrice(settlementPrice);
        classsify.setMeasure(measure);
        classsify.setPreviousProfit(firstDistribution);
        classsify.setPreviousTwoProfit(secondDistribution);

        Boolean aBoolean = classifyService.updateClassify(classsify);
        if (!aBoolean) {
            results = osc.failure("修改失败");
        } else {
            results = osc.success("修改成功");
        }
        return results;
    }

    @ResponseBody
    @PostMapping(value = "/updateIcon",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateIcon(HttpServletRequest request,
                             @RequestParam(value = "icon",required = false) MultipartFile icon,
                             @RequestParam(value = "id",required = false) Integer id){
        System.out.println("开始上传图片了-----------------------------------------------------------");
        String results="";
        if(icon.isEmpty()){
            return osc.failure("图片为空，请上传图片");
        }
        if(id == null || id.equals("")){
            return osc.failure("id为空");
        }
        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/type/";//松注释

        String iconPath = IconPath.ICONPATH+"icon/type/";
//        String iconPathEnum = "E:/job/testIconPath/";
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = icon.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        //设置新文件名称（包含格式）
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            icon.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
        classsify classsify = new classsify();
//        classsify.setIcon("E:/job/testIconPath"+iconName);
//        classsify.setIcon("http://120.79.51.10:8181/dhn/icon/type/"+iconName);
        classsify.setIcon("https://www.dhnep.cn:8181/dhn/icon/type/"+iconName);
        classsify.setId(id);
        Boolean aBoolean = classifyService.updateClassify(classsify);
        if (!aBoolean) {
            results = osc.failure("图片上传失败");
        } else {
            results = osc.success("图片上传成功");
        }
        return results;
    }
}
